// adapter/adapter-manager.js
import { App1Adapter } from './app1-adapter'
import { App2Adapter } from './app2-adapter'
import { IOSAdapter } from './ios-adapter'
import { AndroidAdapter } from './android-adapter'
import { WechatMiniProgramAdapter } from './wechat-miniprogram-adapter'

export class AdapterManager {
  constructor() {
    this.adapters = []
    this.currentAdapter = null
    this.registerDefaultAdapters()
  }

  registerDefaultAdapters() {
    // 注册所有内置适配器
    this.registerAdapter('app1', App1Adapter)
    this.registerAdapter('app2', App2Adapter)
    this.registerAdapter('ios', IOSAdapter)
    this.registerAdapter('android', AndroidAdapter)
    this.registerAdapter('wechat_miniprogram', WechatMiniProgramAdapter)
  }

  registerAdapter(name, AdapterClass) {
    this.adapters.push({
      name,
      Class: AdapterClass
    })
  }

  async autoDetect() {
    for (const adapterInfo of this.adapters) {
      const adapter = new adapterInfo.Class()

      if (adapter.isMatch()) {
        await adapter.init()
        this.currentAdapter = adapter
        console.log(`检测到适配器: ${adapterInfo.name}`)
        return adapter
      }
    }

    // 如果没有匹配的适配器，使用Web适配器
    console.warn('未检测到特定APP环境，使用Web适配器')
    this.currentAdapter = new WebAdapter()
    return this.currentAdapter
  }

  getCurrentAdapter() {
    return this.currentAdapter
  }

  // 手动设置适配器（用于测试或特定场景）
  setAdapter(adapter) {
    this.currentAdapter = adapter
  }
}

// Web适配器（兜底）
class WebAdapter extends BaseAdapter {
  isMatch() {
    return true // 总是匹配，作为兜底
  }

  async invoke(method, params = {}) {
    console.warn(`Web环境模拟调用: ${method}`, params)

    // 在Web环境下模拟一些功能
    switch (method) {
      case 'login':
        return this.mockLogin()
      case 'getUserInfo':
        return this.mockUserInfo()
      default:
        throw new Error(`Web环境不支持: ${method}`)
    }
  }

  mockLogin() {
    return {
      success: true,
      token: 'mock_token_' + Date.now(),
      userId: 'mock_user_123'
    }
  }

  mockUserInfo() {
    return {
      userId: 'mock_user_123',
      nickname: '测试用户',
      avatar: 'https://placeholder.com/avatar.png'
    }
  }
}

export const adapterManager = new AdapterManager()